package com.test.view;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.test.dao.ExcelUtil;
import com.test.dao.TestScoresDao;
import com.test.model.TestScores;

public class UserTestScoresView extends JFrame {

    public JPanel thePanel;

    private JPanel jPAddTestScores;  //学生新增
    private JPanel jPTestScoresManager ; //学生管理

    private JPanel jPButton ; //按钮框

    //设置label
    private JLabel jLid_test_scores;  //学生姓名
    private JTextField txtid_test_scores; //学生姓名文本框
    private JLabel jLnumber_student;
    private JTextField txtnumber_student;
    private JLabel jLid_course;
    private JTextField txtid_course;
    //出生日期
    private JLabel jLtest_score;
    private JTextField txttest_score;

    //数据表
    private JTable jTTestScores;

    //学生操作按钮
    private JButton jbAdd,jbEdit,jbExport,jbDeleteSelected;  //新增，删除，删除选中项

    private JLabel jLFindKeyword;  //查找关键字
    private JTextField txtFindKeyword; //查找关键字
    private JComboBox jcbFindKeyword; //查找关键字
    private JLabel jLSortKeyword;  //排序关键字
    private JTextField txtSortKeyword; //查找关键字
    private JComboBox jcbSortKeyword; //查找关键字

    private List<TestScores> TestScoresList = new ArrayList<TestScores>();

    TestScoresDao testScoDao = new TestScoresDao();

    /** Creates new form MainFrm */
    public UserTestScoresView() {
        initComponents();
        // 设置最大化
        //this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        //this.setPreferredSize(new Dimension(430, 340));
        //this.setPreferredSize(new Dimension(430, 340));
        this.setSize(800, 360);
        //初始化学生列表
        this.beginTestScoresList();

        //设置表单数据
        this.fillTable();
    }

    /**
     * 页面初始话
     */
    private void initComponents() {

        jPAddTestScores = new JPanel();  //学生新增页面
        jPTestScoresManager = new JPanel();  //学生管理页面

        jPButton = new JPanel();  //按钮框
        jPButton.setLayout(new GridLayout(3,2));

        thePanel = new JPanel();

        thePanel.setLayout(new GridLayout(1,2));
        thePanel.add(jPAddTestScores);
        thePanel.add(jPTestScoresManager);

        thePanel.setSize(500,360);
        jPAddTestScores.setSize(100,360);
        jPTestScoresManager.setSize(400,360);

        //增加新增学生的页面
        jLid_test_scores = new JLabel("成绩编号");
        jLnumber_student = new JLabel("学号");
        jLid_course = new JLabel("课程号");
        jLtest_score = new JLabel("成绩");

        jLid_test_scores.setHorizontalAlignment(JLabel.RIGHT);
        jLnumber_student.setHorizontalAlignment(JLabel.RIGHT);
        jLid_course.setHorizontalAlignment(JLabel.RIGHT);
        jLtest_score.setHorizontalAlignment(JLabel.RIGHT);

        jLid_test_scores.setVisible(false);

        jLid_test_scores.setSize(40, 30);
        jLnumber_student.setSize(40, 30);
        jLid_course.setSize(40, 30);
        jLtest_score.setSize(40, 30);

        txtid_test_scores = new JTextField();
        txtnumber_student = new JTextField();
        txtid_course = new JTextField();
        txttest_score = new JTextField();

        txtid_test_scores.setVisible(false);


        txtid_test_scores.setSize(70, 30);
        txtnumber_student.setSize(70, 30);
        txtid_course.setSize(70, 30);
        txttest_score.setSize(70, 30);


        //将新增学生页面添加
        jPAddTestScores.setLayout(new GridLayout(4,2));
        jPAddTestScores.add(jLid_test_scores);
        jPAddTestScores.add(txtid_test_scores);
        jPAddTestScores.add(jLnumber_student);
        jPAddTestScores.add(txtnumber_student);
        jPAddTestScores.add(jLid_course);
        jPAddTestScores.add(txtid_course);
        jPAddTestScores.add(jLtest_score);
        jPAddTestScores.add(txttest_score);
        //数据查看页面
        jPTestScoresManager.setLayout(new GridLayout(3,1,0,0));

        //学生表
        jTTestScores = new JTable();
        jTTestScores.setModel(new DefaultTableModel(new Object[][] {}, new String[] {"学号", "课程号", "成绩"}) {
            boolean[] canEdit = new boolean[] { false, false, false };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });

        jTTestScores.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                bookTypeTableMousePressed(evt);
            }
        });

        jTTestScores.setVisible(true);
        jTTestScores.setSize(400,40);

        //jpTable.add(jTcomputerTable);
        //jP_Browse.add(jpTable);
        JTableHeader jTableHeader = jTTestScores.getTableHeader();
        jTableHeader.setSize(400,240);

        jPTestScoresManager.add(jTableHeader);
        jPTestScoresManager.add(jTTestScores);
        jPTestScoresManager.setPreferredSize(new Dimension(300, 300));

        //设置操作按钮
        jbAdd = new JButton("添加");
        jbAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAdd(evt);
            }
        });

        //设置操作按钮
        jbEdit = new JButton("修改");
        jbEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbEdit(evt);
            }
        });

        //设置操作按钮
        jbExport = new JButton("导出");
        jbExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    export();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        jbDeleteSelected = new JButton("删除选中项");
        jbDeleteSelected.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbDeleteSelect(evt);
            }
        });

        jLFindKeyword = new JLabel("查找关键字");
        txtFindKeyword = new JTextField();
        jLSortKeyword = new JLabel("排序关键字");
        txtSortKeyword = new JTextField();

        jcbFindKeyword = new JComboBox();
        jcbFindKeyword.addItem("学号");
        jcbFindKeyword.addItem("课程号");
        jcbFindKeyword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                findEvent(evt);
            }
        });

        jcbSortKeyword = new JComboBox();
        jcbSortKeyword.addItem("学号");
        jcbSortKeyword.addItem("课程号");
        jcbSortKeyword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sortEvent(evt);
            }
        });

        //jPButton.add(jbAdd);
        //jPButton.add(jbDeleteSelected);
        jPButton.add(jLFindKeyword);
        jPButton.add(jcbFindKeyword);
        //jPButton.add(jbEdit);
        jPButton.add(jbExport);
        jPButton.setSize(400,80);

        jPTestScoresManager.add(jPButton);

        this.add(thePanel);
    }

    /*
     * 学生信息表里的鼠标监听
     * @param evt
     */
    private void bookTypeTableMousePressed(java.awt.event.MouseEvent evt) {
        // 获取选中的行
        int row = jTTestScores.getSelectedRow();
    }

    /**
     * 添加按钮的鼠标监听
     * @param evt
     */
    private void jbAdd(java.awt.event.ActionEvent evt) {
        System.out.println("---添加按钮");

        String id_test_scores = txtid_test_scores.getText() ;
        String number_student = txtnumber_student.getText() ;
        String id_course = txtid_course.getText() ;
        String test_score = txttest_score.getText() ;

        TestScores stu = new TestScores(id_test_scores, number_student, id_course,test_score );

        try {
            testScoDao.AddTestScoress(id_test_scores, number_student, id_course, test_score);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //保存新增学生
        this.TestScoresList.add(stu);
        //修改学生列表
        this.fillTable();

    }

    /**
     * 添加按钮的鼠标监听
     * @param evt
     */
    private void jbEdit(java.awt.event.ActionEvent evt) {
        System.out.println("---修改按钮");

        String id_test_scores = txtid_test_scores.getText() ;
        String number_student = txtnumber_student.getText() ;
        String id_course = txtid_course.getText() ;
        String test_score = txttest_score.getText() ;

        String number_studentTxt = txtnumber_student.getText() ;
        String id_courseTxt = txtid_course.getText() ;

        TestScores stu = new TestScores(id_test_scores, number_student, id_course,test_score );

        try {
            testScoDao.UpdateTestScoressById(id_test_scores, number_student, id_course, test_score);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        List<TestScores> theTestScoresList = new ArrayList<TestScores>();

        theTestScoresList.add(stu);

        // 获取选中的行
        int row = jTTestScores.getSelectedRow();
        int allrow = jTTestScores.getRowCount();
        //System.out.println("--rowCount : " + allrow);
        id_test_scores = "0" ;
        number_student = "0" ;
        id_course = "0" ;
        test_score = "0" ;

        //jTTestScores.remove(row);

        //将删除后的列表存储
        for(int i=0 ;i< allrow ;i++){
            //id_test_scores = (String)jTTestScores.getValueAt(i, 0);
            number_student = (String)jTTestScores.getValueAt(i, 0);
            id_course = (String)jTTestScores.getValueAt(i, 1);
            test_score = (String)jTTestScores.getValueAt(i, 2);

            stu = new TestScores(id_test_scores, number_student, id_course, test_score);

            if(number_studentTxt.equals(number_student) && id_courseTxt.equals(id_course) ){


            } else {
                theTestScoresList.add(stu);
            }
        }


        //保存新增学生
        this.TestScoresList = theTestScoresList;
        //修改学生列表
        this.fillTable();

    }

    /**
     * 删除选中项按钮的监听
     * @param evt
     */
    private void jbDeleteSelect(java.awt.event.ActionEvent evt) {
        System.out.println("---删除选中项");
        // 获取选中的行
        int row = jTTestScores.getSelectedRow();
        int allrow = jTTestScores.getRowCount();
        //System.out.println("--rowCount : " + allrow);
        String id_test_scores = "0" ;
        String number_student ;
        String id_course ;
        String test_score ;

        //jTTestScores.remove(row);

        //System.out.println("--" +stuName +" : " + birthday +" : "+ sex);

        List<TestScores> theTestScoresList = new ArrayList<TestScores>();

        //将删除后的列表存储
        for(int i=0 ;i< allrow ;i++){
            //id_test_scores = (String)jTTestScores.getValueAt(i, 0);
            number_student = (String)jTTestScores.getValueAt(i, 0);
            id_course = (String)jTTestScores.getValueAt(i, 1);
            test_score = (String)jTTestScores.getValueAt(i, 2);

            TestScores stu = new TestScores(id_test_scores, number_student, id_course, test_score);

            if(i == row ){

                //删除选中的成绩信息
                try {
                    testScoDao.DeleteTestScoressById(id_test_scores);
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                theTestScoresList.add(stu);
            }
        }
        //新的学生列表覆盖原有学生列表
        this.TestScoresList = theTestScoresList ;

        //修改学生列表
        this.fillTable();
    }

    /**
     * 查找筛选框
     * @param evt
     */
    private void findEvent(java.awt.event.ActionEvent evt) {
        System.out.println("---查找筛选框");
        String findStr = (String) jcbFindKeyword.getSelectedItem();
        String sortStrName = "学号" ;
        System.out.println("--筛选字段 " + findStr );

        int allrow = jTTestScores.getRowCount();

        String id_test_scores ;
        String number_student ;
        String id_course ;
        String test_score ;

        String thestuName = txtnumber_student.getText() ;  //姓名
        String thebirthday = txtid_course.getText();

        boolean selected = false ;

        List<TestScores> selectedTestScoresList = new ArrayList<TestScores>();

        for(TestScores stu : TestScoresList){
            number_student = stu.getNumber_student();   //姓名
            id_course = stu.getId_course();  //出生年月日

            selected = false ;

            //判断按学生名称筛选还是按出生日期筛选
            if(sortStrName == findStr ){
                if(thestuName.equals(number_student)){
                    selected = true ;
                }
            } else {
                if(thebirthday.equals(id_course)){
                    selected = true ;
                }
            }

            if(selected){
                selectedTestScoresList.add(stu);
            }
        }

        //将数据更新
        this.fillTable(selectedTestScoresList);
    }

    /**
     * 排序框
     * @param evt
     */
    private void sortEvent(java.awt.event.ActionEvent evt) {
        System.out.println("---排序选中项");
        String sortStr = (String) jcbSortKeyword.getSelectedItem();
        System.out.println("== " + sortStr);
        String sortStrName = "学号" ;
        String sortStrBirthday = "课程号" ;

        //进行排序操作

        if(sortStrName.equals(sortStr)){
            Collections.sort(this.TestScoresList,new Comparator<TestScores>() {
                @Override
                public int compare(TestScores o1, TestScores o2) {
                    return o1.getNumber_student().compareTo(o2.getNumber_student()) ;
                }
            });
        } else {
            Collections.sort(this.TestScoresList,new Comparator<TestScores>() {
                @Override
                public int compare(TestScores o1, TestScores o2) {
                    return o1.getId_course().compareTo(o2.getId_course()) ;
                }
            });
        }
        System.out.println(this.TestScoresList);

        //设置表单数据
        this.fillTable();
    }



    private void beginTestScoresList() {

        this.TestScoresList = new ArrayList<TestScores>();

        try {
            this.TestScoresList = testScoDao.getAllTestScoress();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void fillTable() {
        DefaultTableModel dtm = (DefaultTableModel) jTTestScores.getModel();
        dtm.setRowCount(0);
        try {

            for(TestScores stu : TestScoresList){
                //设置每一行
                Vector v = new Vector();

                v.add(stu.getNumber_student());
                v.add(stu.getId_course());
                v.add(stu.getTest_score());
                dtm.addRow(v);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

        }
    }


    private void fillTable(List<TestScores> theTestScoresList) {
        DefaultTableModel dtm = (DefaultTableModel) jTTestScores.getModel();
        dtm.setRowCount(0);
        try {

            for(TestScores stu : theTestScoresList){
                //设置每一行
                Vector v = new Vector();

                v.add(stu.getNumber_student());
                v.add(stu.getId_course());
                v.add(stu.getTest_score());
                dtm.addRow(v);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

        }
    }

    public void export() throws Exception {
        List<TestScores> ScoresList11 = new ArrayList<TestScores>();

        ScoresList11 = this.TestScoresList;
        //excel标题
        String[] title = {"学号","课程号","成绩"};
        String fileName = ".\\erport\\学生成绩表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "学生成绩表";
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, ScoresList11, null);

        StringBuffer fileNameBuffer = new StringBuffer();

        try {
            FileOutputStream fout = new FileOutputStream(fileName);
            wb.write(fout);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UserTestScoresView().setVisible(true);
            }
        });
    }

}
